<template>
	<view>
		<view class="header-container" v-if="showTitle">
			<!-- 状态栏占位 -->
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
			<!-- 标题栏内容 -->
			<view class="gui-flex gui-nowrap gui-rows gui-align-items-center gui-bg-white title-content">
				<gui-header-leading @goBack="goBack" :back="true" :home="false"></gui-header-leading>
				<view class="gui-flex1 gui-text-center" style="margin-left: 80rpx;">
					<text class="gui-h4 gui-ellipsis">{{title}}</text>
				</view>
				<view style="width: 160rpx; display: flex; align-items: center;" @click="goHome" @longtap="aa">
					<image style="width: 40rpx; height: 40rpx;" src="../../static/home/home.png" mode=""></image>
					<view style="font-size: 25rpx; margin-left: 6rpx;">返回首页</view>
				</view>
			</view>
		</view>

		<view class="web-container">
			<web-view :webview-styles="webviewStyles" :src="url" update-title="true" @message="getMessage"
				class="web-view" :style="webviewStyle"></web-view>
		</view>
		
	</view>
</template>

<script>
	import grace from '../../Grace6/js/grace';
	import CryptoJS from '@/Grace6/js/crypto-js.js'
	// import encBase64url from 'crypto-js/enc-base64url';
	var wv;
	export default {
		data() {
			return {
				title: '',
				url: '',
				showTitle:true,
				headerStyle: "background-color:#ffffff;color:#cccccc;",
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				homePage: '/pages/switchPages/index',
				pageHeight: '300rpx',
				back_page: '',
				// title: null,
				// url: "https://app.lgwisdomunion/app.html#/craftsmanSchool/index",
				// localUrl: localUrl,
				// index: 0,
				// msg: "",
				// width: 400,
				// height: 400,
				// config: {
				// 	progressColor: "#ff00ff",
				// 	scrollIndicator: false
				// },
				// testUrl: "http://192.168.11.10:8080/cookie/a",
				// testHost: "192.168.11.10",
				member: null,
				user: null,
				token: null,
				code: '',
				statusBarHeight: 0,
				headerHeight: 30, // 标题栏高度
				webviewStyle: {}
			}
		},
		created() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			// 计算web-view的样式
			const totalHeaderHeight = this.statusBarHeight + this.headerHeight; // 20是title-content的padding
			this.webviewStyle = {
				position: 'fixed',
				top: totalHeaderHeight + 'rpx',
				left: '0',
				right: '0',
				bottom: '0',
				width: '100%',
				height: `calc(100vh - ${totalHeaderHeight}rpx)`
			};
		},
		onLoad(opt) {
			this.member = uni.getStorageSync("member");
			this.user = uni.getStorageSync("userInfo");
			this.token = uni.getStorageSync("ttsxAuthToken");
			console.log("web->opt", opt);
			let info = uni.getWindowInfo();
			if (opt.back) {
				this.back_page = opt.back;
				console.log("back_page", this.back_page);
			} else {
				this.back_page = "pages/switchPages/main";
			}
			if (opt.title) {
				if (opt.title.length <= 8 && opt.title != '悬浮按钮') {
					uni.setNavigationBarTitle({
						title: opt.title,
					})
					this.title = opt.title;
				}
			}
			
			if(opt.showTitle && opt.showTitle == 'false'){
				console.log('opt.showTitle',opt.showTitle);
				this.showTitle = false
			}

			this.pageHeight = info.windowHeight;
			let userInfo = this.camelCaseJsonKeys(uni.getStorageSync("userInfo"));
			if (!userInfo) uni.redirectTo({
				url: "/pages/login/login"
			});
			let self = this;


			let is_local = false; //是否为本项目页面
			//本项目的H5页面
			if (opt.url.indexOf(this.$public_config.H5Url) >= 0) {
				is_local = true;
			}

			if (opt.Bearer || is_local) {
				//卡包和缴费等new-app的H5页面使用Bearer参数，不使用code
				let Bearer = uni.getStorageSync("Bearer");

				this.url = opt.url + "?Bearer=" + Bearer;
				console.log(this.url);
				return;
			}

			//其它H5使用code参数，通过mcode获取code,然后在后台接口通过解码接口获取用户Bearer
			this.$boya.NGet("/tpi/mcode", null, function(res) {
				console.log("mcode", res);
				self.code = res.data;
				if (opt.url.indexOf("app.lgwisdomunion") > 0 || opt.url.indexOf("www.lgwisdomunion") > 0 ||
					opt.url.indexOf("lgadmin.lgwisdomunion") > 0) {
					// 天拓页面
					opt.url = opt.url
				} else if (opt.url.indexOf("lgzy.boyaltd") > 0) {
					// 柳钢康养服务
					opt.url = opt.url + "?token=" + res.data;
				} else {
					opt.url = opt.url + "?code=" + res.data;
				}
				if (opt.url.indexOf("new.lgwisdomunion") > 0) {
					//唯品会/美的跳转
					self.external(opt);
				} else {
					self.url_to(opt);
				}
			}, function(err) {
				uni.showToast({
					title: "登录过期，请重新登录！"
				})
				uni.reLaunch({
					url: "/pages/login/login"
				})
			})
		},

		onReady() {
			// // #ifdef APP-PLUS
			// var currentWebview = this.$scope.$getAppWebview();
			// setTimeout(() => {
			// 	const totalHeaderHeight = this.statusBarHeight + this.headerHeight;
			// 	let wv = currentWebview.children()[0];
			// 	wv.setStyle({
			// 		top: totalHeaderHeight,
			// 		height: `calc(100vh - ${totalHeaderHeight}px)`,
			// 		position: 'fixed',
			// 		left: 0,
			// 		right: 0,
			// 		bottom: 0
			// 	});
			// }, 100);
			// // #endif
			// #ifdef APP-PLUS
			var currentWebview = this.$scope.$getAppWebview()
			setTimeout(function() {
				wv = currentWebview.children()[0]
				let info = uni.getSystemInfoSync();
				console.log("systemInfo", info);
				wv.setStyle({
					top: info.statusBarHeight + 35,
					height: info.screenHeight - (info.statusBarHeight + 36)
				})
			
			}, 1500);
			// #endif
		},
		methods: {
			url_to(parm) {
				let self = this

				var link = parm.url;
				if (parm.url.indexOf("app.lgwisdomunion") > 0 || parm.url.indexOf("www.lgwisdomunion") > 0) {
					//"a6e38217-32c9-4c9e-8a69-1bc7cb563a50"
					let url = parm.url;
					url = url.split('#')[1];
					let userinfo = self.user;
					let removeKey = ['orga', 'politicCountenance', 'political',
						'procreationRemark', 'procreationStatus', 'education', 'educationalBackground', 'email',
						'fileAge', 'fullTime', 'headPortrait', 'crtIp', 'crtTime', 'crtUser',
						'updIp', 'updTime', 'updUser', 'speciality', 'maritalStatus', 'academicDegree',
						'procreation_remark', 'procreation_status', 'politic_countenance', 'join_tradeUnion_time',
						'join_company_time', 'academicDegree',
					]
					for (let key in removeKey) {
						delete userinfo[removeKey[key]];
					}

					let _url = "https://app.lgwisdomunion.cn/#/loginx?code=" + this.code + "&url=" + url;
					self.url = _url;
					console.log(_url);
					return;
				}
				// if (parm.url.indexOf("jf.boyaltd") > 0) {
				if (parm.url.indexOf("jf.lgwisdomunion") > 0) {

					let _url = parm.url;
					if (_url.charAt(_url.length - 1) == '/') {
						_url = _url.slice(0, -1);
					}
					self.url = _url;

				} else {

					link = link.replace("{uuid}", self.member.uuid)

					// link = link.replace("{phone}", self.member.phone)

					link = link.replace("{name}", self.member.name)

					// link = link.replace("{sfz}", self.member.sfz)

					// link = link.replace("{lg_id}", self.user.user_name)

					link = link.replace("{token}", self.token)

					let Bearer = uni.getStorageSync("Bearer");
					link = link.replace("{Bearer}", "Bearer");

					link = link.replace("{userName}", self.member.lg_id)

					link = link.replace("{ttsxAuthToken}", self.token);

					let timestamp1 = new Date().getTime();
					link = link.replace("{timestamp}", timestamp1);

					link = link.replace("{ttsx_userid}", self.user.id);


					// 柳钢康养服务用
					let keyStr = CryptoJS.enc.Utf8.parse('96df30d7f54d41c0f3c6eb60caf2eea9');
					let ivStr = CryptoJS.enc.Utf8.parse('b1aeb14d7e22c4c5');

					function encrypt(word) {
						let encrypted = CryptoJS.AES.encrypt(word, keyStr, {
							iv: ivStr,
							mode: CryptoJS.mode.CBC,
							padding: CryptoJS.pad.Pkcs7
						});
						return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
					}

					// let plainText = self.member.uuid + '|' + self.member.chinaname;
					let encryption = encrypt(self.member.uuid + '|' + self.member.chinaname);
					let encryptedText = btoa(encryption)
					link = link.replace("{uuid-name}", encryptedText)
					// console.log('康养: ', encryption);

					// 职工书屋用
					if (link.indexOf("{md5_sign}") >= 0) {
						let host = link.substring(0, link.indexOf("?"));
						console.log("host", host);
						let urlparm = link.substring(link.indexOf("?"));

						let searchParams = self.StrToObj(urlparm);
						let paramsObj = {};
						for (let key in searchParams) {
							let value = searchParams[key];
							if (value.indexOf('{md5_sign}') == -1) {
								paramsObj[key] = value;
							}
						}
						// searchParams.forEach((value, param) => {
						// 	if(value!='{md5_sign}'){
						// 		paramsObj[param] = value;
						// 	}
						// });
						paramsObj["time"] = Date.parse(new Date()) / 1000 - 3600;
						let a = self.objToStr(paramsObj);
						let sign = grace.md5(a);
						paramsObj["sign"] = sign;
						link = host + "?" + self.objToStr(paramsObj);
						// let m="appID=lzgt&appKey=12fds4d6sg9pr66c9s57vva2c30l9ded&userName=19821024&userId=b73a7471-d415-45b5-9087-3fd3914b3093&time=1705318101";
						// console.log("md5",grace.md5(m));
					}
					self.url = link;
				}
				console.log("web->url", self.url);
			},
			external(parm) {
				/**
				 * 唯品会和美的的跳转
				 */
				let self = this
				if (parm.url.indexOf("wph") > 0) {
					console.log('接口：', parm.url);
					uni.request({
						url: parm.url,
						method: "GET",
						data: {
							uuid: self.member.uuid
						},
						success(res) {
							console.log('我是唯品会data: ', res.data);
							if (res.data.code == 200) {
								let _url = res.data.data.data.JumpLink
								parm.url = _url
								self.url = _url
								// window.location.href = url
								console.log('唯品会链接: ', res.data.data.data.JumpLink);
							} else {
								self.$boya.msg(res.msg)
							}
						}
					})
					return;
				}

				if (parm.url.indexOf("meifu") > 0) {
					console.log('接口：', parm.url);
					uni.request({
						url: parm.url,
						method: "POST",
						data: {
							// mobile: 13877211150,
							// user_name: '魏颖斌',
							// account: 81601008,
							mobile: self.user.phone_number,
							user_name: self.user.real_name,
							account: self.user.company_num
						},
						success(res) {
							console.log('我是新美福data: ', res.data);
							if (res.data.code == 200) {
								let _url = res.data.data.data.JumpLink
								parm.url = _url
								self.url = _url
								// window.location.href = url
								console.log('新美福链接: ', res.data.data.data.JumpLink);
							} else {
								self.$boya.msg(res.msg)
							}
						}
					})
					return;
				}
				if (parm.url.indexOf("tpi") > 0) {
					console.log("tpi", parm.url);
					let path = parm.url.split("/");
					let _url = "/tpi/" + path[path.length - 1];
					this.$boya.NGet(_url, {
						code: this.code
					}, function(res) {
						console.log(res);
						if (res.data) {
							self.url = res.data;
						}
					})
				}

			},
			// 柳钢康养服务参数加密
			encrypt(word) {
				let encrypted = CryptoJS.AES.encrypt(word, keyStr, {
					iv: ivStr,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
				return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
			},
			StrToObj(queryString) {
				const params = {};
				const queryStringWithoutQuestionMark = queryString.substring(1); // 去掉问号
				const keyValuePairs = queryStringWithoutQuestionMark.split('&');

				for (let pair of keyValuePairs) {
					const [key, value] = pair.split('=');
					params[key] = value;
				}

				return params;
			},

			objToStr(obj) {
				let paramsText = "";
				for (const i in obj) {
					if (obj[i]) {
						paramsText += i + "=" + obj[i] + "&";
					}
				}
				paramsText = paramsText.slice(0, paramsText.length - 1);
				return paramsText;
			},
			camelCaseJsonKeys(json) {
				const result = {};

				for (const key in json) {


					const camelKey = key.replace(/_(\w)/g, function(match, p1) {
						return p1.toUpperCase();
					});
					result[camelKey] = json[key];
				}
				console.log('userInfo: ', result);
				return result;
			},
			aa() {
				uni.setClipboardData({
					data: this.url,
					success() {
						uni.showToast({
							title: "ok"
						})
					}
					// "/craftsmanSchool/index"
					//  /craftsmanSchool/index
					//http://lg.boyaltd.cn/#/login?login=eyJ1c2VySW5mbyI6eyJ1c2VyTmFtZSI6IjE5ODIxMDI0IiwicmVhbE5hbWUiOiLpmYjlpKfotoUiLCJoZWFkUG9ydHJhaXQiOiIiLCJzdGF0dXMiOjAsInBob25lTnVtYmVyIjoiMTc3MDc3MTE4MTUiLCJlbWFpbCI6IiIsInNleCI6MSwiYWdlIjo0MCwib3JnSWQiOiIyNDk5MWQ5Mi1mNDJmLTQxNjctODk1NS04YWRlMWIyNTJiNTMiLCJpZE5vIjoiNDUwMjA1MTk4MjEwMjQxMzMyIiwiYmlydGhEYXRlIjoiMTk4Mi0xMC0yNCAwMDowMDowMCIsImRldmljZXNUaW1lIjoiMjAyMy0wMS0xMiAxNjoyNzozNSIsIm9yZ05hbWUiOiLljZrkuprnp5HmioAiLCJkZXB0SWQiOiI3ZmE2NDVkOS00YTc5LTRmNTUtYjEyMS1jMzQwM2ExZWIxNjQiLCJpZk1lbWJlciI6MCwidmVyaWZ5U3RhdHVzIjoxLCJlZHVjYXRpb24iOiIiLCJtZW1iZXJOdW0iOiIiLCJjb21wYW55TnVtIjoiMTk4MjEwMjQiLCJhZGRyZXNzIjoiIiwibmF0dXJlIjoi6ZuG5ZuiIiwidXNlclR5cGUiOjAsIndvcmtTdGF0dXMiOiLlnKjlspciLCJtYXJpdGFsU3RhdHVzIjoiIiwiZWR1Y2F0aW9uYWxCYWNrZ3JvdW5kIjoiIiwiYWNhZGVtaWNEZWdyZWUiOiIiLCJwb2xpdGljQ291bnRlbmFuY2UiOiIiLCJwcm9jcmVhdGlvblN0YXR1cyI6IiIsInNwZWNpYWxpdHkiOiIiLCJwb3N0Ijoi5rWL6K%2BV5Lq65ZGYIiwic3RhdGVCcyI6IkZIMDEiLCJiaXJ0aGRheVNjb3JlIjowLCJmaXJzdExvZ2luU2NvcmUiOjAsImlkIjoiYjczYTc0NzEtZDQxNS00NWI1LTkwODctM2ZkMzkxNGIzMDkzIiwiY3J0VXNlciI6Ijg2NTA3NzIzIiwiY3J0VGltZSI6IjIwMjMtMDEtMTIgMTY6Mjc6MzUiLCJjcnRJcCI6IjE5Mi4xNjguMS4zMSIsInVwZFRpbWUiOiIyMDIzLTA3LTMxIDE1OjI1OjUwIn0sInBsYXRmb3JtTWFsbCI6ImM2OWE3MGM1LWRlNmYtNDRmYS1hMzMzLTg4YzVhNWIzZmY3NyIsInRva2VuIjoiZWU5YzU5NWUtYWZiMy00YWI4LWFiYTMtMGY1ZGE0NzY1MTYyIiwidXJsIjoiL2NyYWZ0c21hblNjaG9vbC9pbmRleCJ9
				})
			},
			goBack() {
				console.log("goBack", this.back_page);
				// uni.reLaunch({
				// 	url: "/" + this.back_page + "?back=web"
				// })
				uni.navigateBack({
					delta: 1
				});
			},
			goHome() {
				uni.reLaunch({
					url: "/" + this.back_page + "?back=web"
				})
			},
			getMessage(e) {
				console.log("web->getMessage", JSON.stringify(e));
				let self = this;
				let dev = uni.getStorageSync("is_PreviewVer")
				if (e.detail.data[0].type == "title") {
					console.log("set_title", e.detail.data[0].data.title);
					this.title = e.detail.data[0].data.title;
					uni.setNavigationBarTitle({
						title: e.detail.data[0].data.title
					})
					return;
				}
				if (dev) {
					uni.showModal({
						title: "接收参数",
						content: JSON.stringify(e.detail),
						showCancel: false,
						success: function() {
							self.$comm.web_message(e);
						}
					})
				} else {
					this.$comm.web_message(e);
				}

			}
		}
	}
</script>

<style scoped>
	.header-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: #fff;
		/* 添加阴影效果 */
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.status-bar {
		width: 100%;
		background-color: #ffffff;
	}

	.title-content {
		/* padding: 10rpx 0; */
		height: 44px;
		box-sizing: border-box;
		/* 添加底部边线 */
		border-bottom: 1rpx solid #eee;
		/* 可以选择性添加内部阴影,突出立体感 */
		background: linear-gradient(to bottom, #ffffff, #fafafa);
	}

	.web-container {
		position: relative;
		width: 100%;
		/* height: 100vh; */
		box-sizing: border-box;
	}

	.web-view {
		width: 100%;
		height: 100%;
		background: #fff;
	}
</style>